package org.linlinjava.litemall.db.handler;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.linlinjava.litemall.db.dto.WebOrderGoodsRemarkDTO;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class OrderGoodsRemarkListTypeHandler extends BaseTypeHandler<List<WebOrderGoodsRemarkDTO>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<WebOrderGoodsRemarkDTO> parameter, JdbcType jdbcType) throws SQLException {
        String jsonString = JSONUtil.toJsonStr(parameter);
        ps.setString(i, jsonString);
    }

    @Override
    public List<WebOrderGoodsRemarkDTO> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String jsonString = rs.getString(columnName);
        return parseJsonString(jsonString);
    }

    @Override
    public List<WebOrderGoodsRemarkDTO> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String jsonString = rs.getString(columnIndex);
        return parseJsonString(jsonString);
    }

    @Override
    public List<WebOrderGoodsRemarkDTO> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String jsonString = cs.getString(columnIndex);
        return parseJsonString(jsonString);
    }

    private List<WebOrderGoodsRemarkDTO> parseJsonString(String jsonString) {
        try {
            //之前下单的订单格式不对所以会转换失败
            if (jsonString == null || jsonString.isEmpty()) {
                return null;
            }
            JSONArray jsonArray = JSONUtil.parseArray(jsonString);
            return Convert.toList(WebOrderGoodsRemarkDTO.class, jsonArray);
        }catch (Exception e){
            //转换失败的返回null
            return null;
        }
    }
}
